package com.dlc.shop.distribution.common.listener;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dlc.shop.bean.event.UserDestroyEvent;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.distribution.common.model.*;
import com.dlc.shop.distribution.common.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author gaozijie
 * @date 2023-11-03
 */
@Slf4j
@Component
@AllArgsConstructor
public class DistributionUserDestroyListener {

    private final DistributionUserService distributionUserService;
    private final DistributionUserBanService distributionUserBanService;
    private final DistributionUserBindService distributionUserBindService;
    private final DistributionUserWalletService distributionUserWalletService;
    private final DistributionUserWalletBillService distributionUserWalletBillService;
    private final DistributionUserIncomeService distributionUserIncomeService;
    private final DistributionWithdrawCashService distributionWithdrawCashService;
    private final DistributionAuditingService distributionAuditingService;

    @EventListener(UserDestroyEvent.class)
    public void userDestroyListener(UserDestroyEvent event) {
        String userId = event.getUserId();
        log.info("用户[{}]注销，清除相关分销信息....", userId);
        this.clearDistributionInfo(userId);
        log.info("分销相关信息清除完成！");
    }

    /**
     * 清除分销信息
     * @param userId 用户id
     */
    private void clearDistributionInfo(String userId) {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            return;
        }
        // 删除分销员相关信息
        Long distributionUserId = distributionUser.getDistributionUserId();
        distributionUserService.removeById(distributionUserId);
        distributionUserBanService.remove(new LambdaQueryWrapper<DistributionUserBan>()
                .eq(DistributionUserBan::getDistributionUserId, distributionUserId));
        // 删除分销钱包相关信息
        Long walletId = distributionUserWalletService.getWalletIdByDistributionUserId(distributionUserId);
        distributionUserWalletService.removeById(walletId);
        distributionUserWalletBillService.remove(new LambdaQueryWrapper<DistributionUserWalletBill>()
                .eq(DistributionUserWalletBill::getWalletId, walletId));
        distributionUserIncomeService.remove(new LambdaQueryWrapper<DistributionUserIncome>()
                .eq(DistributionUserIncome::getWalletId, walletId));
        distributionWithdrawCashService.remove(new LambdaQueryWrapper<DistributionWithdrawCash>()
                .eq(DistributionWithdrawCash::getWalletId, walletId));
        // 更新分销员等级
        this.updateDistributionUserGrade(distributionUser);
        // 失效客户绑定关系
        distributionUserBindService.update(new LambdaUpdateWrapper<DistributionUserBind>()
                .set(DistributionUserBind::getState, -1)
                .set(DistributionUserBind::getInvalidReason, 4)
                .set(DistributionUserBind::getInvalidTime, new Date())
                .eq(DistributionUserBind::getDistributionUserId, distributionUserId));
        // 删除分销审核记录
        distributionAuditingService.remove(new LambdaQueryWrapper<DistributionAuditing>()
                .eq(DistributionAuditing::getDistributionUserId, distributionUserId));
    }

    /**
     * 更新分销员等级
     * @param distributionUser 分销员
     */
    private void updateDistributionUserGrade(DistributionUser distributionUser) {
        Long distributionUserId = distributionUser.getDistributionUserId();
        // 修改直接子分销员（将自己的parentId, parentIds和grade直接赋值给子分销员）
        // (因为parentId和parentIds有可能为null，只能通过wrapper更新，正常接口null值会不进行更新)
        distributionUserService.update(new LambdaUpdateWrapper<DistributionUser>()
                .set(DistributionUser::getParentId, distributionUser.getParentId())
                .set(DistributionUser::getParentIds, distributionUser.getParentIds())
                .set(DistributionUser::getGrade, distributionUser.getGrade())
                .eq(DistributionUser::getParentId, distributionUserId));
        // 查出所有间接子分销员（将grade-1，并从parentIds路径中移除自己的id）
        List<DistributionUser> subDistributionUsers = distributionUserService.list(new LambdaQueryWrapper<DistributionUser>()
                .like(DistributionUser::getParentIds, StrUtil.COMMA + distributionUserId + StrUtil.COMMA)
                .ne(DistributionUser::getParentId, distributionUserId));
        if (!CollectionUtils.isEmpty(subDistributionUsers)) {
            for (DistributionUser subDistributionUser : subDistributionUsers) {
                subDistributionUser.setGrade(subDistributionUser.getGrade() - 1);
                subDistributionUser.setParentIds(subDistributionUser.getParentIds().replace(StrUtil.COMMA + distributionUserId + StrUtil.COMMA, StrUtil.COMMA));
            }
            distributionUserService.updateBatchById(subDistributionUsers);
        }
    }
}
